package netty.inaction;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Date;

/**
 * @Author: DRevelation
 * @Date: 2021/3/11 13:21
 */
public class EchoClient2 {

    private final String host;
    private final int port;

    public EchoClient2(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup g = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(g).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new EchoClientHandler2());
                    }
                });
        try {
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture();
        } finally {
            g.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoClient2("localhost", 65535).start();
    }
}
